/**
 * Copyright (c) 2017, 西安星沙网络科技-版权所有
 *
 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.gnu.org/licenses/lgpl-3.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.waleychain.exchange.consumer.controller.wallet;

import java.math.BigDecimal;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import cn.waleychain.exchange.consumer.controller.BaseController;
import cn.waleychain.exchange.core.constant.DDIC;
import cn.waleychain.exchange.core.entity.PageInfo;
import cn.waleychain.exchange.core.logger.LoggerHelper;
import cn.waleychain.exchange.core.result.DefaultResult;
import cn.waleychain.exchange.core.result.IBaseResult;
import cn.waleychain.exchange.core.vaildate.VaildateHelper;
import cn.waleychain.exchange.feign.CoinWalletServiceFeign;
import cn.waleychain.exchange.model.CoinWallet;
import cn.waleychain.exchange.model.WalletRecharge;
import cn.waleychain.exchange.model.WalletWithdraw;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(description = "平台钱包账号相关接口")
@RestController
@RequestMapping("api/v1/coinWallet")
public class CoinWalletController extends BaseController {

	private static final Logger mLog = LoggerFactory.getLogger(CoinWalletController.class);
	
	@Autowired
	private CoinWalletServiceFeign coinWalletFeign;
	
	@RequestMapping(value = "/fetchCoinWalletList", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value = "获取用户平台钱包账号列表", notes = "获取用户平台钱包账号列表，URL: http://{ip}:{port}/{projectName}/api/v1/coinWallet/fetchCoinWalletList", httpMethod = "GET", response = DefaultResult.class)
	public IBaseResult fetchUserCoinWalletList (
			@ApiParam(value = "用户标识ID", required = false) @RequestParam(required = false) Long userId,
			@ApiParam(value = "币种标识ID", required = false) @RequestParam(required = false) Long coinId,
			@ApiParam(value = "手机号", required = false) @RequestParam(required = false) String mobile,
			@ApiParam(value = "钱包地址", required = false) @RequestParam(required = false) String address,
			@ApiParam(value = "状态（1 正常 2 冻结）", required = false) @RequestParam(required = false) Integer status,
			@ApiParam(value = "排序列（1 余额 2 冻结资金）", required = false) @RequestParam(required = false) Integer orderColumn,
			@ApiParam(value = "排序类型（1 升序 2 降序）", required = false) @RequestParam(required = false) Integer orderType,
			@ApiParam(value = "每次查询多少条数据", required = true) @RequestParam(required = true, defaultValue = "-1") Integer showCount, 
			@ApiParam(value = "当前查询页", required = true) @RequestParam(required = true, defaultValue = "1") Integer currentPage, 
			@RequestHeader String Authorization) throws Exception {

		try {
			
			PageInfo<CoinWallet> page = coinWalletFeign.fetchCoinWalletList(userId, coinId, mobile, address, status, orderColumn, orderType, showCount, currentPage);
			
			return DefaultResult.buildSuccessResult(page);
		} catch (Exception e) {
			LoggerHelper.printLogError(mLog, e, "获取用户平台钱包账号列表");
		}

		return DefaultResult.buildFailedResult();
	}
	
	@RequestMapping(value = "/fetchCoinWalletInfo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value = "获取用户平台钱包账号信息", notes = "获取用户平台钱包账号信息，URL: http://{ip}:{port}/{projectName}/api/v1/coinWallet/fetchCoinWalletInfo", httpMethod = "GET", response = DefaultResult.class)
	public IBaseResult fetchCoinWalletInfo (
			@ApiParam(value = "用户标识ID", required = true) @RequestParam Long userId,
			@ApiParam(value = "币种ID", required = true) @RequestParam Long coinId,
			@RequestHeader String Authorization) throws Exception {

		try {
			
			CoinWallet info = coinWalletFeign.fetchCoinWalletInfo(userId, coinId);
			
			return DefaultResult.buildSuccessResult(info);
		} catch (Exception e) {
			LoggerHelper.printLogError(mLog, e, "获取用户平台钱包账号信息");
		}

		return DefaultResult.buildFailedResult();
	}
	
	@RequestMapping(value = "/userApplyWithdraw", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value = "用户钱包提现申请", notes = "用户钱包提现申请，URL: http://{ip}:{port}/{projectName}/api/v1/coinWallet/userApplyWithdraw", httpMethod = "POST", response = DefaultResult.class)
	public IBaseResult userWithdraw(
			@ApiParam(value = "用户标识ID", required = true) @RequestParam Long userId, 
			@ApiParam(value = "用户平台钱包标识ID", required = true) @RequestParam Long coinWalletId,
			@ApiParam(value = "用户个人钱包标识ID", required = true) @RequestParam Long userWalletId,
			@ApiParam(value = "提现金额", required = true) @RequestParam BigDecimal amount,
			@ApiParam(value = "动态验证码", required = true) @RequestParam String mobileCode,
			@ApiParam(value = "交易密码", required = true) @RequestParam String payPassword,
			@RequestHeader String Authorization) throws Exception {

		try {

			boolean result = coinWalletFeign.userWithdraw(userId, coinWalletId, userWalletId, amount, mobileCode, payPassword);
			
			return DefaultResult.buildResult(result);
		} catch (Exception e) {
			LoggerHelper.printLogError(mLog, e, "用户钱包提现申请");
		}

		return DefaultResult.buildFailedResult();
	}
	
	@RequestMapping(value = "/withdrawReview", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value = "用户钱包提现审核", notes = "用户钱包提现审核，URL: http://{ip}:{port}/{projectName}/api/v1/coinWallet/withdrawReview", httpMethod = "POST", response = DefaultResult.class)
	public IBaseResult setAccountWithdrawStatus (
			@ApiParam(value = "提现标识ID", required = true) @RequestParam Long idNo,
			@ApiParam(value = "状态（31 完成 32 审核拒绝 ）") @RequestParam Integer status,
			@ApiParam(value = "备注说明", required = false) @RequestParam(required = false) String remark,
			@RequestHeader String Authorization) throws Exception {

		try {

			VaildateHelper.vaildateIntParams(status, "状态", DDIC.WalletChangeStatus.STATUS_31.id, DDIC.WalletChangeStatus.STATUS_32.id);
			
			boolean result = coinWalletFeign.setAccountWithdrawStatus(idNo, status, remark);

			return DefaultResult.buildResult(result);
		} catch (Exception e) {
			LoggerHelper.printLogError(mLog, e, "用户钱包提现审核");
		}

		return DefaultResult.buildFailedResult();
	}
	
	@RequestMapping(value = "/userCancelWithdraw", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value = "用户撤销提现", notes = "用户撤销提现，URL: http://{ip}:{port}/{projectName}/api/v1/coinWallet/userCancelWithdraw", httpMethod = "POST", response = DefaultResult.class)
	public IBaseResult cancelWalletOut (
			@ApiParam(value = "提现标识ID", required = true) @RequestParam Long idNo,
			@RequestHeader String Authorization) throws Exception {

		try {

			boolean result = coinWalletFeign.userCancelWithdraw(idNo);

			return DefaultResult.buildResult(result);
		} catch (Exception e) {
			LoggerHelper.printLogError(mLog, e, "用户撤销提现");
		}

		return DefaultResult.buildFailedResult();
	}

	@RequestMapping(value = "/sendCoinSuccess", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value = "给用户打币成功，更新用户提币状态", notes = "给用户打币成功，更新用户提币状态，URL: http://{ip}:{port}/{projectName}/api/v1/coinWallet/sendCoinSuccess", httpMethod = "POST", response = DefaultResult.class)
	public IBaseResult sendCoinSuccess (
			@ApiParam(value = "提现标识ID", required = true) @RequestParam Long idNo,
			@ApiParam(value = "交易标识ID", required = true) @RequestParam String txId,
			@RequestHeader String Authorization) throws Exception {

		try {

			boolean result = coinWalletFeign.sendCoinSuccess(idNo, txId);

			return DefaultResult.buildResult(result);
		} catch (Exception e) {
			LoggerHelper.printLogError(mLog, e, "给用户打币成功，更新用户提币状态");
		}

		return DefaultResult.buildFailedResult();
	}
	
	@RequestMapping(value = "/fetchWithdrawWalletList", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value = "获取钱包提现记录列表", notes = "获取钱包提现记录列表，URL: http://{ip}:{port}/{projectName}/api/v1/coinWallet/fetchWithdrawWalletList", httpMethod = "GET", response = DefaultResult.class)
	public IBaseResult fetchWithdrawWalletList (
			@ApiParam(value = "用户平台钱包标识ID", required = false) @RequestParam(required = false) Long coinWalletId,
			@ApiParam(value = "用户名称", required = false) @RequestParam(required = false) String userName,
			@ApiParam(value = "币种标识ID", required = false) @RequestParam(required = false) Long coinId,
			@ApiParam(value = "手机号", required = false) @RequestParam(required = false) String mobile,
			@ApiParam(value = "状态（30 待审核 31 通过 32 审核拒绝 33 用户撤销 34 打币中）", required = false) @RequestParam(required = false) Integer status,
			@ApiParam(value = "开始时间", required = false) @RequestParam(required = false) Date begindate,
			@ApiParam(value = "结束时间", required = false) @RequestParam(required = false) Date endDate,
			@ApiParam(value = "每次查询多少条数据", required = true) @RequestParam(required = true, defaultValue = "-1") Integer showCount, 
			@ApiParam(value = "当前查询页", required = true) @RequestParam(required = true, defaultValue = "1") Integer currentPage,  
			@RequestHeader String Authorization) throws Exception {

		try {
			
			PageInfo<WalletWithdraw> list = coinWalletFeign.fetchWalletWithdrawPageList(coinWalletId, userName, status, coinId, mobile, begindate, endDate, showCount, currentPage);
			
			return DefaultResult.buildSuccessResult(list);
		} catch (Exception e) {
			LoggerHelper.printLogError(mLog, e, "获取钱包提现记录列表");
		}

		return DefaultResult.buildFailedResult();
	}
	
	@RequestMapping(value = "/fetchRechargeWalletList", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value = "获取钱包充值记录列表", notes = "获取钱包充值记录列表，URL: http://{ip}:{port}/{projectName}/api/v1/coinWallet/fetchRechargeWalletList", httpMethod = "GET", response = DefaultResult.class)
	public IBaseResult fetchRechargeWalletList (
			@ApiParam(value = "用户平台钱包标识ID", required = false) @RequestParam(required = false) Long coinWalletId,
			@ApiParam(value = "用户名称", required = false) @RequestParam(required = false) String userName,
			@ApiParam(value = "币种标识ID", required = false) @RequestParam(required = false) Long coinId,
			@ApiParam(value = "手机号", required = false) @RequestParam(required = false) String mobile,
			@ApiParam(value = "状态（40 待审核 41 通过）", required = false) @RequestParam(required = false) Integer status,
			@ApiParam(value = "开始时间", required = false) @RequestParam(required = false) Date begindate,
			@ApiParam(value = "结束时间", required = false) @RequestParam(required = false) Date endDate,
			@ApiParam(value = "每次查询多少条数据", required = true) @RequestParam(required = true, defaultValue = "-1") Integer showCount, 
			@ApiParam(value = "当前查询页", required = true) @RequestParam(required = true, defaultValue = "1") Integer currentPage,  
			@RequestHeader String Authorization) throws Exception {

		try {
			
			PageInfo<WalletRecharge> list = coinWalletFeign.fetchWalletRechargePageList(coinWalletId, userName, status, coinId, mobile, begindate, endDate, showCount, currentPage);
			
			return DefaultResult.buildSuccessResult(list);
		} catch (Exception e) {
			LoggerHelper.printLogError(mLog, e, "获取钱包充值记录列表");
		}

		return DefaultResult.buildFailedResult();
	}
	
	@RequestMapping(value = "/freezeAndUnfreezeWallet", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value = "冻结解冻账号", notes = "冻结解冻账号，URL: http://{ip}:{port}/{projectName}/api/v1/coinWallet/userCancelWithdraw", httpMethod = "POST", response = DefaultResult.class)
	public IBaseResult freezeAndUnfreezeWallet (
			@ApiParam(value = "账号标识ID", required = true) @RequestParam Long coinWalletId,
			@ApiParam(value = "状态（1 正常 2 冻结）", required = true) @RequestParam Integer status,
			@RequestHeader String Authorization) throws Exception {

		try {

			VaildateHelper.vaildateIntParams(status, "状态", DDIC.CoinWalletStatus.NORMAL.id, DDIC.CoinWalletStatus.FREEZE.id);
			
			boolean result = coinWalletFeign.freezeAndUnfreezeWallet(coinWalletId, status);

			return DefaultResult.buildResult(result);
		} catch (Exception e) {
			LoggerHelper.printLogError(mLog, e, "冻结解冻账号");
		}

		return DefaultResult.buildFailedResult();
	}
	
}
